//
//  SEGShareHelpCardView.m
//  SEGUhomeStandard
//
//  Created by 揭婧雯 on 2018/10/22.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGShareHelpCardView.h"
#import "SEGShareImageBottomView.h"

@interface SEGShareHelpCardView ()
/**
 图片
 */
@property (nonatomic, strong)UIImageView *imageView;

/**
 内容标签
 */
@property (nonatomic, strong)SEGLabel *contentLabel;
/**
 内容高度
 */
@property (nonatomic, assign) CGFloat contentLabelHeight;

/**
 联系人标签
 */
@property (nonatomic, strong)UILabel *contactLabel;

/**
 联系方式标签
 */
@property (nonatomic, strong)UILabel *contactInformationLabel;

/**
 视图宽度
 */
@property (nonatomic, assign) CGFloat viewWidth;

@property (nonatomic, strong) SEGShareImageBottomView *bottomContainerView;

@end

@implementation SEGShareHelpCardView
- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

/// 生成分享的图片
- (UIImage *)generateShareHelpCardImage
{
    [self setUpUIWithIsShowView:NO];
    self.backgroundColor = [UIColor whiteColor];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.superview);
        make.width.mas_equalTo(self.viewWidth);
        make.height.mas_equalTo(self.viewHeight);
    }];

    // 开启上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.viewWidth, self.viewHeight), NO, 0);
    // 获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 渲染图层到上下文
    [self.layer renderInContext:context];
    // 从上下文中获取图片
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭上下文
    UIGraphicsEndImageContext();
    return image;
}

- (void)setHelpCardModel:(SEGShareHelpCardModel *)helpCardModel
{
    _helpCardModel = helpCardModel;
    /// 生成分享的弹窗显示界面
    [self setUpUIWithIsShowView:YES];
}

///isShowView是否为显示的视图
- (void)setUpUIWithIsShowView:(BOOL)isShowView
{
    if (!self.helpCardModel) {
        return;
    }
    
    [self removeAllSubviews];
    
    self.viewHeight = 0;
    CGFloat xPadding;//控件的左右间距
    CGFloat imageTopPadding;//图片的顶部间距
    CGFloat imageXPadding;//图片的左右间距
    CGFloat topContentPadding = 15.0;//内容的顶部间距
    if (isShowView) {
        self.viewWidth = kScreenWidth - 30;
        xPadding = 15;
        imageTopPadding = 0;
        imageXPadding = 0;
        if (!self.helpCardModel.image) {//没有图片时 顶部距离20
            topContentPadding = 20.0;
        }
    }else {
        self.viewWidth = 290;
        xPadding = 10;
        imageTopPadding = 2.5;
        imageXPadding = 2.5;
    }
    
    //图片
    if (self.helpCardModel.image) {
        CGFloat imageHeight = (self.viewWidth / 3.0) * 2;//图片比例3:2
        UIImageView *imageView = [[UIImageView alloc] initWithImage:self.helpCardModel.image];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;//截取合适部分显示
        imageView.backgroundColor = [UIColor colorWithHexString:@"#ffc40d"];
        [self addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(imageXPadding);
            make.right.equalTo(self).offset(-imageXPadding);
            make.top.equalTo(self).offset(imageTopPadding);
            make.height.mas_equalTo(imageHeight);
        }];
        self.viewHeight += imageHeight;
    }
    
    //内容
    self.viewHeight += topContentPadding;
    self.contentLabel = [self seg_createContentLabelWithXPaddding:xPadding isShowView:isShowView];
    self.viewHeight += self.contentLabelHeight;
    
    // 联系人上面的分割线
    BOOL hasContect = (self.helpCardModel.contact && self.helpCardModel.contact.length > 0) ||
    (self.helpCardModel.contactInformation && self.helpCardModel.contactInformation.length > 0);
    if (hasContect) {//只要有就加线
        self.viewHeight += 15.0;
        //分隔线
        UIImageView* lineView = [[UIImageView alloc] init];
        //        lineView.backgroundColor = kColor_L2;
        lineView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"img_fabu_dotted_line")];
        [self addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(xPadding);
            make.right.equalTo(self).offset(-xPadding);
            make.height.mas_equalTo(0.5);
            make.top.equalTo(self).offset(self.viewHeight);
        }];
        self.viewHeight += 0.5;
    }
    
    //联系人
    if (self.helpCardModel.contact && self.helpCardModel.contact.length > 0) {
        self.viewHeight += 15;//顶部间距

        self.contactLabel = [self seg_createContactLabelWithPadding:xPadding];
        self.contactLabel.text = [NSString stringWithFormat:@"联系人：%@",self.helpCardModel.contact];
        CGFloat labelHeight = [self.contactLabel sizeThatFits:CGSizeMake(self.viewWidth - xPadding * 2, HUGE)].height;
        self.viewHeight += labelHeight;
    }
    
    //联系方式
    if (self.helpCardModel.contactInformation && self.helpCardModel.contactInformation.length > 0) {
        //顶部间距
        if (self.helpCardModel.contact && self.helpCardModel.contact.length > 0) {//有联系人
            self.viewHeight += 5;
        }else {
            self.viewHeight += 15;
        }

        self.contactInformationLabel = [self seg_createContactLabelWithPadding:xPadding];
        self.contactInformationLabel.text = [NSString stringWithFormat:@"联系方式：%@",self.helpCardModel.contactInformation];
        CGFloat labelHeight = [self.contactInformationLabel sizeThatFits:CGSizeMake(self.viewWidth - xPadding * 2, HUGE)].height;
        self.viewHeight += labelHeight;
    }
        
    
    if (isShowView) {
        [self seg_separatorLineAndLabel];
    }else {
        self.viewHeight += 15;
        
        [self.bottomContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(self.mas_top).offset(self.viewHeight);
            make.height.mas_equalTo(70);
        }];
        
        // 默认下载链接
        NSString *shareString = @"http://www.uhomecp.com/uhome_download.html";//默认下载链接
        
        UIImage *qrImage = [shareString createQRForSize:300];
        self.bottomContainerView.qrCodeImage = qrImage;
        
        self.viewHeight += 70;
    }
}

//创建联系人或联系方式标签
- (UILabel *)seg_createContactLabelWithPadding:(CGFloat)xPadding
{
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor colorWithHexString:@"#333333"];
    label.font = kFont_13;
    label.textAlignment = NSTextAlignmentLeft;
    label.numberOfLines = 0;
//    label.text = [NSString stringWithFormat:@"联系方式：%@",self.helpCardModel.contactInformation];
    [self addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(xPadding);
        make.right.equalTo(self).offset(-xPadding);
        make.top.equalTo(self).offset(self.viewHeight);
    }];
//    CGFloat labelHeight = [label sizeThatFits:CGSizeMake(self.viewWidth, HUGE)].height;
//    self.viewHeight += labelHeight;
    return label;
}

//帮助内容和分享按钮的分隔线和分享标语
- (void)seg_separatorLineAndLabel
{
    //帮助内容和分享按钮的分隔线 带缺口(上下各5间距)
    self.viewHeight += 5.0;//和上面文字的间距
    UIImageView* lineView = [[UIImageView alloc] init];
    
    if (@available(iOS 13.0, *)) {
        lineView.backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kColor_bg3;
            } else {
                return kColor_W;
            }
        }];
    }else {
        lineView.backgroundColor = kColor_bg3;
    }
    
    lineView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"img_bg_line")];
    [self addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(0);
        make.right.equalTo(self).offset(-0);
        make.top.equalTo(self).offset(self.viewHeight);
    }];
    CGFloat lineHeight = lineView.image.size.height;
    self.viewHeight += lineHeight;
    self.viewHeight += 5;//和下面文字的间距
    
    //标题
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor colorWithHexString:@"#666666"];
    label.font = kFont_13;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"分享到业主群，互帮互助";
    [self addSubview:label];
    CGFloat height = label.font.lineHeight;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self);
        make.top.equalTo(self).offset(self.viewHeight);
        make.height.mas_equalTo(height);
    }];
    self.viewHeight += height;
    
    UIView *leftLine = [[UIView alloc] init];
    leftLine.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
    [self addSubview:leftLine];
    [leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(label.mas_left).offset(-5);
        make.centerY.equalTo(label);
        make.height.mas_equalTo(0.5);
        make.width.mas_equalTo(20);
    }];
    
    UIView *rightLine = [[UIView alloc] init];
    rightLine.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
    [self addSubview:rightLine];
    [rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_right).offset(5);
        make.centerY.equalTo(label);
        make.height.mas_equalTo(0.5);
        make.width.mas_equalTo(20);
    }];
    
    //底部间距
    self.viewHeight += 23;
}


//互助描述内容
- (SEGLabel *)seg_createContentLabelWithXPaddding:(CGFloat)xPadding isShowView:(BOOL)isShowView
{
    SEGLabel *contentLabel = [[SEGLabel alloc]init];
    contentLabel.userInteractionEnabled = NO;
    contentLabel.textAlignment = NSTextAlignmentLeft;
    contentLabel.textVerticalAlignment = SEGTextVerticalAlignmentCenter;
    contentLabel.displaysAsynchronously = NO;
    contentLabel.ignoreCommonProperties = YES;//YES会影响系统属性
    contentLabel.numberOfLines = 0;
    contentLabel.lineBreakMode = NSLineBreakByTruncatingTail;
//    contentLabel.
    
    CGFloat labelWidth = self.viewWidth - xPadding * 2;
    CGFloat fontSize = 16.0;
    CGFloat linePadding = 7;//行距
    UIFont *font = [UIFont boldSystemFontOfSize:fontSize];
    CGFloat oneLineHeight = [self heightForString:@"单行" font:font width:labelWidth];
    
    NSString *typeText = [NSString stringWithFormat:@" %@ ",self.helpCardModel.helpType];
    NSString *contentText = [NSString stringWithFormat:@"%@  %@", typeText, self.helpCardModel.helpContent];//加上图片位置计算行数
    
    if(isShowView) {//显示的时候需要根据行数区分字体大小
        CGFloat height = [self heightForString:contentText font:font width:labelWidth];
        CGFloat count2 = height / oneLineHeight;
        if (count2 > 3) {
            fontSize = 13.0;
            linePadding = 6;
            font = [UIFont boldSystemFontOfSize:fontSize];
        }
    }

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:contentText];
    text.yy_font = font;
    text.yy_color = [UIColor colorWithHexString:@"#333333"];
    
    NSRange typeRange = [contentText rangeOfString:typeText];
    SEGTextBorder *border = [SEGTextBorder borderWithFillColor:[UIColor colorWithHexString:@"#ffc40d"] cornerRadius:2];
    border.insets = UIEdgeInsetsMake(-1, 0, -1, 0);
    [text yy_setTextBackgroundBorder:border range:typeRange];
    [text yy_setColor:[UIColor colorWithHexString:@"#333333"] range:typeRange];
    [text yy_setFont:kFont_13 range:typeRange];
   
    SEGContentTextLinePositionModifier *modifier = [SEGContentTextLinePositionModifier new];
    modifier.font = font;
    modifier.paddingTop = linePadding;
    modifier.paddingBottom = linePadding;
    
    SEGTextContainer *container = [SEGTextContainer new];
    container.size = CGSizeMake(labelWidth, HUGE);
    container.linePositionModifier = modifier;
    
    SEGTextLayout *contentLabelTextLayout = [SEGTextLayout layoutWithContainer:container text:text];
    //        if (!contentLabelTextLayout) return self.viewHeight;
    contentLabel.textLayout = contentLabelTextLayout;
    
    self.contentLabelHeight = [modifier heightForLineCount:contentLabelTextLayout.rowCount];
    [self addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(xPadding);
        make.right.equalTo(self).offset(-xPadding);
        make.top.equalTo(self).offset(self.viewHeight);
        make.height.mas_equalTo(self.contentLabelHeight);
    }];
    
//    contentLabel.backgroundColor = kColor_3;
    
    return contentLabel;
}


- (CGFloat)heightForString:(NSString *)string font:(UIFont *)font width:(CGFloat)width {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, MAXFLOAT)];
    label.text = string;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.bounds.size.height;
    return height;
}

- (SEGShareImageBottomView *)bottomContainerView {
    if (!_bottomContainerView) {
        _bottomContainerView = [[SEGShareImageBottomView alloc] init];
//        _bottomContainerView.backgroundColor = kColor_bg;
        [self addSubview:_bottomContainerView];
    }
    return _bottomContainerView;
}

@end
